/*
 * @Descripttion: 移动端咨询模块接口
 * @version: 
 * @Author: 
 * @Date: 2022-04-26 13:30:15
 * @LastEditors: weidelong
 * @LastEditTime: 2022-05-05 17:15:04
 */
const express = require('express')
const jwt = require("../jwt/jwt")
const doctor = require('../db/doctorSchema')
const doctormsg = require('../db/doctorMsgSchema') // 聊天记录

const router = express.Router()

// 查询对应科室医师列表
router.get('/selectDepartmentDoctor', async (req, res) => {
	const { department } = req.query
    // console.log(department)
    let doctorList = await doctor.find({department})
    if (doctorList) {
        const list = doctorList.map(i => {
            return {
                id: i.id,
                name: i.userName,
                department: i.department,
                docImg: "/img/doctor.79a77d88.png",
                unit: i.unit,
                title: i.title,
                sex: i.sex,
                phone: i.phone,
                strengths: i.strengths,
                addTime: i.addTime,
				state: i.state
            }
        })
        res.send({
            status: 200,
            data: {
                code: 0,
                doctorList: list
            },
            msg: '查询成功'
        })
    } else {
        res.send({
            status: 404,
            msg: '查询失败'
        })
    }
})

/* 移动端存储与医师的聊天记录 */
router.post('/saveDoctorMsg', async (req, res) => {
	const msg = req.body
    let haveMsg = await doctormsg.find({})
    // 如果数据库没有数据
    if (haveMsg.length == 0) {
        doctormsg.create(msg, (err, result) => {
            if (err) {
                throw error
            } else {
                res.send({
                    status: 200,
                    data: {
                        code: 0,
                    },
                    msg: '添加成功'
                })
            }
        })
    } else {
        doctormsg.updateOne({}, msg, (err, docs) => {
            if (err) {
                throw err
            } else {
                res.send({
                    status: 200,
                    data: {
                        code: 0,
                    },
                    msg: '操作成功'
                })
            }
        })
    }
})

/* 移动端读取与医师的聊天记录 */
router.get('/searchDoctorMsg', async (req, res) => {
    let msgList = await doctormsg.find({})
    if (msgList) {
        if (msgList.length == 0) {
            res.send({
                status: 200,
                data: {
                    code: 0,
                    msgList
                },
                msg: '查询成功'
            })
        } else {
            let msg = JSON.parse(msgList[0].msg)
            res.send({
                status: 200,
                data: {
                    code: 0,
                    msgList
                },
                msg: '查询成功'
            })
        }
        
    } else {
        res.send({
            status: 500,
            msg: '查询失败'
        })
    }
})

module.exports = router